package com.mairuide.httpclient;

import com.mairuide._frame.utils.ListUtils;
import com.mairuide._frame.utils.NetworkConnect;
import com.mairuide._frame.utils.PhonePlace;
import com.mairuide.phone.callanalysis.entity.PhoneMapDetail;
import com.mairuide.phonebaseinfo.pojo.BS_460;
import com.mairuide.phonebaseinfo.service.PhoneInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Created by 敲代码的卡卡罗特
 * on 2018/12/19 14:06.
 */
@Component
public class BaseSite {

    @Resource
    private RestTemplate restTemplate;
    @Autowired
    private PhoneInfoService phoneInfoService;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     *
     * @author 刘中华
     * @date 2018/12/19 14:14
     * @param [ids]
     * @return java.util.Map
     * @Description 通过多个id获取信息list集合   比如传入 111,222,333
     */
    public Map getCallInfoByIds(String ids){
        String[] split = ids.split(",");
        List<String> strings = Arrays.asList(split);
        HashSet hashSet = new HashSet(strings);
        strings=new ArrayList<>(hashSet);
        ids=StringUtils.join(strings,",");
        Map result = new HashMap();
        if (NetworkConnect.checkNetwork()){//如果联网就进行远程校验
            Map<String, String> map = new HashMap<>();
            map.put("ids",ids);
            result = restTemplate.postForObject("http://47.105.197.249:8888/base-site/call/list",map, Map.class);
        }else{
            String regex="[\\d,]+";
            Pattern pattern = Pattern.compile(regex);
            Matcher match=pattern.matcher(ids);
            boolean b=match.matches();
            List list = new ArrayList<>();
            if (b){
                /*String[] split = ids.split(",");
                List<String> strings = Arrays.asList(split);
                HashSet hashSet = new HashSet(strings);
                strings=new ArrayList<>(hashSet);*/
                if (strings.size()>500){
                    List<List<String>> lists = ListUtils.splitList2(strings, 500);
                    for (List l:lists){
                        List obj = phoneInfoService.getPhoneInfoByIds(l);
                        list.addAll(obj);
                    }
                }else{
                    list = phoneInfoService.getPhoneInfoByIds(strings);
                }
                ArrayList<Map<String, Object>> list1 = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    BS_460 BS_460 = (BS_460)list.get(i);
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("id",BS_460.getId());
                    map.put("mnc",BS_460.getMNC());
                    map.put("mcc",BS_460.getMCC());
                    map.put("ac",BS_460.getAC());
                    map.put("ci",BS_460.getCI());
                    map.put("address",BS_460.getADDRESS());
                    map.put("lat",BS_460.getLAT());
                    map.put("lng",BS_460.getLNG());
                    map.put("roads",BS_460.getROADS());
                    map.put("lnga",BS_460.getLNGA());
                    map.put("radius",BS_460.getRADIUS());
                    map.put("lata",BS_460.getLATA());
                    map.put("latb",BS_460.getLATB());
                    map.put("ver",BS_460.getVER());
                    map.put("lngb",BS_460.getLNGB());
                    map.put("latg",BS_460.getLATG());
                    map.put("lngg",BS_460.getLNGG());
                    map.put("ref",BS_460.getREF());
                    map.put("rid",BS_460.getRID());
                    map.put("rids",BS_460.getRIDS());
                    list1.add(map);
                }
                result.put("code",20000);
                result.put("data",list1);
            }
        }
        return result;
    }

    /**
     *
     * @author 刘中华
     * @date 2018/1/24 14:14
     * @param [ids]
     * @return java.util.Map
     * @Description 通过cpuid来获取详情
     */
    public Map<String,Object> getCompanyDetailById(String id){
        Map<String, Object> params = new HashMap<>();
        params.put("cpuid", id);
        Map<String,Object> map=restTemplate.getForObject("http://47.105.197.249:8888/base-site/user/{cpuid}",Map.class,params);
        return map;
    }
    /**
     *
     * @author 刘中华
     * @date 2018/12/23 17:28
     * @param [maps]
     * @return java.lang.String
     * @Description  得到查询的id
     */
    public static String getBaseSiteIds(List<Map<String,Object>> maps){

        List<String> baseIdList= maps.stream().map(m->{
            String cid = (String) m.get("CID");
            String lac = (String) m.get("LAC");
            String SERVICE_NUMBER = (String) m.get("SERVICE_NUMBER");
            if(StringUtils.isNotBlank(cid)&&StringUtils.isNotBlank(lac)&&!"0".equals(cid)&&!"0".equals(lac)){
                String s1="";
                String s2="";
                if(lac.length()<5){
                    int a=5-lac.length();
                    for(int i=0;i<a;i++){
                        s1+="0";
                    }
                }
                if(cid.length()<9){
                    int a=9-cid.length();
                    for(int i=0;i<a;i++){
                        s2+="0";
                    }
                }
                lac=s1+lac;
                cid=s2+cid;
                String chinaMobilePhoneNum = PhonePlace.isChinaMobilePhoneNum(SERVICE_NUMBER);
                String baseId="460"+chinaMobilePhoneNum+lac+cid;
                return baseId.replaceAll(" ","");
            }
            return "";
        }).collect(Collectors.toList());
        String a="";
        for(String s:baseIdList){
            if (StringUtils.isNotBlank(s)){
                a+=s+",";
            }
        }
        if (StringUtils.isNotBlank(a)){
            a=a.substring(0,a.length()-1);
        }
        return a;
    }
    public static String getBaseSiteIds(Set<PhoneMapDetail> set){

        List<String> baseIdList= set.stream().map(m->{
            String cid = (String) m.getCID();
            String lac = (String) m.getLAC();
            String SERVICE_NUMBER = (String) m.getSERVICE_NUMBER();
            if(StringUtils.isNotBlank(cid)&&StringUtils.isNotBlank(lac)&&!"0".equals(cid)&&!"0".equals(lac)){
                String s1="";
                String s2="";
                if(lac.length()<5){
                    int a=5-lac.length();
                    for(int i=0;i<a;i++){
                        s1+="0";
                    }
                }
                if(cid.length()<9){
                    int a=9-cid.length();
                    for(int i=0;i<a;i++){
                        s2+="0";
                    }
                }
                lac=s1+lac;
                cid=s2+cid;
                String chinaMobilePhoneNum = PhonePlace.isChinaMobilePhoneNum(SERVICE_NUMBER);
                String baseId="460"+chinaMobilePhoneNum+lac+cid;
                return baseId.replaceAll(" ","");
            }
            return "";
        }).collect(Collectors.toList());
        String a="";
        for(String s:baseIdList){
            if (StringUtils.isNotBlank(s)){
                a+=s+",";
            }
        }
        if (StringUtils.isNotBlank(a)){
            a=a.substring(0,a.length()-1);
        }
        return a;
    }

    /**
     *
     * @author 刘中华
     * @date 2018/12/23 17:28
     * @param [maps]
     * @return java.lang.List
     * @Description
     */
    public static List<String> getBaseSiteList(List<Map<String,Object>> maps){
        List<String> baseIdList= maps.stream().map(m->{
            String cid = (String) m.get("CID");
            String lac = (String) m.get("LAC");
            String SERVICE_NUMBER = (String) m.get("SERVICE_NUMBER");
            if(StringUtils.isNotBlank(cid)&&StringUtils.isNotBlank(lac)&&!"0".equals(cid)&&!"0".equals(lac)){
                String s1="";
                String s2="";
                if(lac.length()<5){
                    int a=5-lac.length();
                    for(int i=0;i<a;i++){
                        s1+="0";
                    }
                }
                if(cid.length()<9){
                    int a=9-cid.length();
                    for(int i=0;i<a;i++){
                        s2+="0";
                    }
                }
                lac=s1+lac;
                cid=s2+cid;
                String chinaMobilePhoneNum = PhonePlace.isChinaMobilePhoneNum(SERVICE_NUMBER);
                String baseId="460"+chinaMobilePhoneNum+lac+cid;
                return baseId.replaceAll(" ","");
            }
            return "";
        }).collect(Collectors.toList());
        return baseIdList;
    }
    public static List<String> getBaseSiteList(Set<PhoneMapDetail> set){
        List<String> baseIdList= set.stream().map(m->{
            String cid = (String) m.getCID();
            String lac = (String) m.getLAC();
            String SERVICE_NUMBER = (String) m.getSERVICE_NUMBER();
            if(StringUtils.isNotBlank(cid)&&StringUtils.isNotBlank(lac)&&!"0".equals(cid)&&!"0".equals(lac)){
                String s1="";
                String s2="";
                if(lac.length()<5){
                    int a=5-lac.length();
                    for(int i=0;i<a;i++){
                        s1+="0";
                    }
                }
                if(cid.length()<9){
                    int a=9-cid.length();
                    for(int i=0;i<a;i++){
                        s2+="0";
                    }
                }
                lac=s1+lac;
                cid=s2+cid;
                String chinaMobilePhoneNum = PhonePlace.isChinaMobilePhoneNum(SERVICE_NUMBER);
                String baseId="460"+chinaMobilePhoneNum+lac+cid;
                return baseId.replaceAll(" ","");
            }
            return "";
        }).collect(Collectors.toList());
        return baseIdList;
    }


    //地图封装
    public  List getMap(List<PhoneMapDetail> maps){
        //封装地图数据
        Set<PhoneMapDetail> arrayList_hava = new HashSet<>();//存放有基站信息的数据
        Set<PhoneMapDetail> arrayList_no = new HashSet<>();//存放没有基站信息的数据
        try {
            //大致思路，先遍历下，把没有基站信息的数据领出来，去远程服务器查找（然后更新数据库），有基站信息的就不查了，
            for (int i = 0; i < maps.size(); i++) {
                PhoneMapDetail map = maps.get(i);
                String LNGB =map.getLNGB();
                String LATB =map.getLATB();
                String ADDRESS =map.getADDRESS();
                //因为要滤重，所以用set集合，判断某个对象的几个字段相等就说明这个两个对象相等，所以重写equal方法和hash方法，hash方法字段不能为null，所以，查询的时候
                //默认null是0
                if(LNGB!=null&&LATB!=null&ADDRESS!=null&!"0".equals(LNGB)&&!"0".equals(LATB)&&!"0".equals(ADDRESS)){
                    arrayList_hava.add(map);
                }else{
                    arrayList_no.add(map);
                }
            }
            //从远程服务器上得到地图对象信息
            if (arrayList_no.size()>0){
                Map callInfoByIds = getCallInfoByIds(BaseSite.getBaseSiteIds(arrayList_no));
                //根据已经得到的对象得到ids集合，目的是为了和远程基站信息的id一一对应
                List<String> baseSiteList = BaseSite.getBaseSiteList(arrayList_no);
                List<Map<String,Object>> data = (List<Map<String,Object>>)callInfoByIds.get("data");
                if (data!=null){
                    for (Map<String,Object> m:data){
                        List<PhoneMapDetail> arrayList = new ArrayList<>(arrayList_no);
                        PhoneMapDetail PHONE_RECORDING = arrayList.get(baseSiteList.indexOf((String) m.get("id")));
                        //System.out.println("通话表：》》"+PHONE_RECORDING);
                        //System.out.println("基站表：》》"+m);
                        //把服务器上的基站信息同步到本地
                        String ADDRESS= m.get("address").toString();
                        String LATB= m.get("latb").toString();
                        String LNGB= m.get("lngb").toString();
                        String cid = PHONE_RECORDING.getCID();
                        String lac = PHONE_RECORDING.getLAC();
                        String sql = "update TB_PHONE_RECORDING set ADDRESS='"+ADDRESS+"',LATB='"+LATB+"',LNGB='"+LNGB+"' where cid='"+cid +"' AND LAC='"+lac+"' " ;
                        System.out.println(sql);
                        jdbcTemplate.execute(sql);
                        PHONE_RECORDING.setADDRESS(ADDRESS);
                        PHONE_RECORDING.setLATB(LATB);
                        PHONE_RECORDING.setLNGB(LNGB);
                        arrayList_hava.add(PHONE_RECORDING);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ArrayList<Object> s = new ArrayList<>(arrayList_hava);
        return s;
    }
}
